// Copyright 2017 guangbo. All rights reserved.

//节点配置，节点启动读取
//key: node:nodeName
//节点通用配置，用于服务注册服务发现
//key: nodeRegister
package lib_config

import (
	"encoding/json"
	"gitee.com/goxiang2/server/lib/lib_watch"
	"strings"
)

const (
	NodeKey         = "node:"
	ServiceKey      = "service:"
	NodeRegisterKey = "nodeRegister"
)

//节点配置函数

func GetAllName(client *lib_watch.WatchClient, prefix string) []string {
	var ret []string

	nodes := client.KeyPrefix(prefix)
	for i := 0; i < len(nodes); i++ {
		arr := strings.Split(nodes[i], ":")
		if len(arr) == 2 {
			ret = append(ret, arr[1])
		}
	}

	return ret
}

func GetNodeAllName(client *lib_watch.WatchClient) []string {
	return GetAllName(client, NodeKey)
}

func GetNodeAllConfig(client *lib_watch.WatchClient, nodeName string) map[string]string {
	m := make(map[string]string)
	values := client.Hgetall(NodeKey + nodeName)
	for i := 0; i < len(values); i = i + 2 {
		m[values[i]] = values[i+1]
	}
	return m
}

func SetNodeConfig(client *lib_watch.WatchClient, nodeName, key, value string) {
	client.Hset(NodeKey+nodeName, key, value)
}

func DelNodeConfig(client *lib_watch.WatchClient, nodeName string) {
	client.Del(NodeKey + nodeName)
}

func GetNodeConfig(client *lib_watch.WatchClient, nodeName, key string) string {
	return client.Hget(NodeKey+nodeName, key)
}

//节点注册函数
type NodeInfo struct {
	Name    string
	Address string   //ip:port
	Service []string //服务列表
}

func GetAllRegisterNode(client *lib_watch.WatchClient) map[string]*NodeInfo {
	m := make(map[string]*NodeInfo)
	values := client.Hgetall(NodeRegisterKey)
	for i := 0; i < len(values); i = i + 2 {
		info := &NodeInfo{}
		json.Unmarshal([]byte(values[i+1]), info)
		m[values[i]] = info
	}
	return m
}

func SetRegisterNode(client *lib_watch.WatchClient, nodeName string, info *NodeInfo) {
	buff, _ := json.Marshal(info)
	client.Hset(NodeRegisterKey, nodeName, string(buff))
}

func GetRegisterNode(client *lib_watch.WatchClient, nodeName string) *NodeInfo {
	value := client.Hget(NodeRegisterKey, nodeName)
	info := &NodeInfo{}
	if value == "" {
		return info
	}
	json.Unmarshal([]byte(value), info)
	return info
}
